package com.gis.utils;

import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class DirUtils {
    public static File DirValidate(String dir) {
        if (dir == null || dir.isEmpty()) {
            throw new IllegalArgumentException("Directory path cannot be null or empty");
        }
        File directory = new File(dir);
        if (!directory.exists() || !directory.isDirectory()) {
            throw new IllegalArgumentException("目录不存在或不是一个有效的目录");
        }
        return directory;
    }

    public static List<File> getFilesFromDir(File directory) {
        List<File> files = new ArrayList<>();
        Queue<File> queue = new ArrayDeque<>();
        queue.add(directory);
        while (!queue.isEmpty()) {
            File currentFile = queue.poll();
            if (currentFile.isDirectory()) {
                File[] subFiles = currentFile.listFiles();
                if (subFiles != null) {
                    for (File file : subFiles) {
                        queue.add(file);
                    }
                }
            } else {
                files.add(currentFile);
            }
        }
        return files;
    }

    /**
     * 删除指定目录及其内容
     * @param dir 目录
     */
    public static void deleteDir(String dir) {
        File file = new File(dir);
        Boolean del_res = file.delete();
        if (del_res) {
            return;
        } else {
            throw new RuntimeException("文件目录: " + dir + "删除失败");
        }
    }
    /**
     * 创建目录
     * @param dir 目录路径
     */
    public static void createDir(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            boolean created = file.mkdirs();
            if (!created) {
                throw new RuntimeException("目录创建失败: " + dir);
            }
        }
    }
}
